package com.yeeverse.sdk.vo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeeverse.sdk.util.JsonUtils;
import com.yeeverse.sdk.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

public class RspDataVO<T> {

    private static final String CODE_STR ="code";

    private static final String MSG_STRE="message";

    private static final String DATA_STR="message";



    private String code;

    private String message;

    private T data;

    public RspDataVO(String str, Class<T> clazz) {
        if (StringUtils.isNotBlank(str)) {
            JSONObject json = JSON.parseObject(str);
            this.code = json.getString(CODE_STR);
            this.message = json.getString(MSG_STRE);
            if (json.get("data") != null && StringUtils.isNotBlank(json.getString("data"))) {
                this.data = JSONObject.parseObject(json.getString("data"), clazz);
            }else {
                Map<String, Object> innerMap = json.getInnerMap();
                //非表中data接口，处理返回值
                Map<String,Object> newData=new HashMap<>();
                if(innerMap!=null){
                    for (String key:innerMap.keySet()) {
                        if(CODE_STR.equals(key)||MSG_STRE.equals(key)){
                            continue;
                        }else {
                            newData.put(key,innerMap.get(key));
                        }
                    }
                    this.data = JSONObject.parseObject(JsonUtils.toJsonString(newData), clazz);

                }
            }
        }
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getT(String data, Class<T> clazz) {
        return JSONObject.parseObject(data, clazz);
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}
